﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using Caliburn.Micro;
using MessageLib;

namespace VoiceMessager.ViewModels
{
	public sealed class ConnectViewModel:Screen
	{
		private MainViewModel _mainViewModel;

		public ConnectViewModel(MainViewModel mainViewModel)
		{
			_mainViewModel = mainViewModel;
			this.IpString = _mainViewModel.IpEndPoint.Address.ToString();
			this.PortString = _mainViewModel.IpEndPoint.Port.ToString();
			DisplayName = @"连接设置";
		}

		public void Connect()
		{
			_mainViewModel.IpEndPoint = new IPEndPoint(IPAddress.Parse(IpString),Convert.ToInt32(PortString));
			TryClose();
		}

		public bool CanConnect => !string.IsNullOrEmpty(IpString) &&
		                          !string.IsNullOrEmpty(PortString) &&
		                          Regex.IsMatch(IpString, Statics.IpRegex) &&
		                          _portString.IsNumber(0, 65536);

		private string _ipString;

		public string IpString 
		{
			get { return _ipString; }
			set
			{
				_ipString = value;
				NotifyOfPropertyChange();
				NotifyOfPropertyChange(() => CanConnect);
			}
		}

		private string _portString;
		public string PortString
		{
			get { return _portString; }
			set
			{
				_portString = value;
				NotifyOfPropertyChange();
				NotifyOfPropertyChange(()=>CanConnect);
			}
		}
	}
}
